package cn.ycc1.fibonacci;

/**
 * @author ycc
 * @date 2024/5/31
 */
public class Test {
    public static void main(String[] args) {
        System.out.println(fib(5));
        System.out.println(fib2(5));
        System.out.println(fib3(5));
    }

    // 递归
    public static int fib(int n) {
        if (n == 0 || n == 1) {
            return n;
        }
        return fib(n - 1) + fib(n - 2);
    }

    // 循环
    public static int fib2(int n) {
        int a = 1, b = 1;
        for (int i = 3; i <= n; ++i) {
            a += b;
            b = a - b;
        }
        return a;
    }

    // 动态规划
    public static int fib3(int n) {
        int[] dp = new int[n+1]; // dp[i] 表示第 i 个斐波那契数 i = 2 表示第三个
        dp[0] = 0; // 因为dp[n-2]可能为0，所以需要初始化
        dp[1] = 1;
        for(int i = 2; i <= n; i++) {
            dp[i] = dp[i-1] + dp[i-2];
        }
        return dp[n];
    }

}